from django.shortcuts import render,redirect,reverse,HttpResponse
from crm.forms import RegForm,CustomerForm
from django.db.models import Q
from crm import models
import hashlib


# Create your views here.

def login(request):
    '''登录'''
    if request.method =='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        md5=hashlib.md5()
        md5.update(password.encode('utf-8'))
        obj=models.UserProfile.objects.filter(username=username,password=md5.hexdigest(),is_active=True).first()
        if obj:
            request.session['is_login']=True
            request.session['user_id']=obj.pk
            return render(request,'index.html')
    return render(request,'login.html')

def reg(request):
    '''注册'''
    form_obj=RegForm()
    if request.method =='POST':
        form_obj = RegForm(request.POST)  #获取表单数据
        if form_obj.is_valid():
            #校验表单数据
            form_obj.save()
            return redirect(reverse('login'))

    return render(request,'reg.html',{'form_obj':form_obj})
from django.views import View
from utils.pagination import Pagination
class CustomerList(View):
    def get(self,request, *args, **kwargs):
        q=self.search(['qq','name','phone'])
        if request.path_info == reverse('customer_list'):
            all_customer = models.Customer.objects.filter(q,consultant__isnull=True)  # 公户
        else:
            all_customer = models.Customer.objects.filter(q,consultant_id=request.session.get('user_id'))  #私户
        page = Pagination(request.GET.get('page', 1), all_customer.count(), request.GET.copy(), 2)
        return render(request,'customer_list.html',{'all_customer':all_customer[page.start:page.end],'page_html':page.page_html})

    def post(self,request,*args, **kwargs):
        active=request.POST.get('active')
        if not hasattr(self,active):
            return HttpResponse('非法操作')
        getattr(self,active)()
        return self.get(request, *args, **kwargs)
    def multi_apply(self):
        '''公户转私户'''
        pk=self.request.POST.getlist('pk')
        # 方法一
        models.Customer.objects.filter(pk__in=pk).update(consultant=self.request.user_obj)
    def multi_pub(self):
        '''私户转公户'''
        pk = self.request.POST.getlist('pk')
        # 方法一
        models.Customer.objects.filter(pk__in=pk).update(consultant=None)
    def search(self,field_list):
        query=self.request.GET.get('query','')
        q=Q()
        q.connector='OR'
        for field in field_list:
            q.children.append(Q(('{}__contains'.format(field),query)))
        return q
def customer_change(request,pk=None):
    obj=models.Customer.objects.filter(pk=pk).first()
    form_obj=CustomerForm(instance=obj)  #实例化
    if request.method =='POST':
        form_obj = CustomerForm(request.POST,instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect(reverse('customer_list'))
    title='编辑客户' if pk else '新增客户'
    return render(request, 'form.html',{'form_obj':form_obj,'title':title})

class ConsultList(View):
    # def get(self, request, customer_id=0, *args, **kwargs):
    #     if not customer_id:
    #         # 展示当前销售的所有跟进记录
    #         all_consult = models.ConsultRecord.objects.filter(consultant=request.user_obj, delete_status=False)
    #     else:
    #         # 某一个客户的所有的跟进记录
    #         all_consult = models.ConsultRecord.objects.filter(customer_id=customer_id, delete_status=False)
    #     return render(request, 'consult_list.html',
    #                   {'all_consult': all_consult.order_by('date'), 'customer_id': customer_id})
    pass

def consult_change(request):
    pass


